require 'oauth/consumer'
require 'yaml'
require 'json'
require 'fastercsv'

class ContactController < ApplicationController
  CONSUMER_KEY = "m9vE-mbQW4LaFhLGOfm_tB--r4gwiUCOQbtFxSYEKFr7NE5VVdC0LqVfPYq-RjFU"
  CONSUMER_SECRET = "5yMG_DkglLGvJM5zkE2rg8XSN9KZXmk7PHG9OJC79TI2di7AEhgqq_8bpn3lQ8JX"

  def index
  end

  def output
    path = DataFile.save(params[:upload])
    redirect_to "/contact/linkedin", :filepath => path
  end

  def csv(path)
    @content = IO.readlines(path)
    @content.delete_at(0)
    @names = []
    @content.each do |lines|
      aline = lines.split(",")
      aname = aline[0].split(" ")
      if aname.length >= 2
        @names.push(aline[0].split(" "))
      end
    end
    @names
  end

  def linkedin
    filepath = params[:filepath]==nil ? "public/data/1.csv" : params[:filepath]
    xuwen_oauth_token = "e2d6f3fe-26f3-43a8-b187-b17a42519466"
    xuwen_oauth_secret = "03065342-10b9-46e9-adf1-474ae54ae499"
    oauth_token = xuwen_oauth_token
    oauth_secret = xuwen_oauth_secret

    config = YAML.load_file('config/oauth.yaml')

    oauth_options = config['linkedin']
    # Set up LinkedIn specific OAuth API endpoints
    consumer_options = { :site => oauth_options['api_host'],
    		         :authorize_path => oauth_options['authorize_path'],
                     	 :request_token_path => oauth_options['request_token_path'],
			 :access_token_path => oauth_options['access_token_path'] }

    consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, consumer_options)
    access_token = OAuth::AccessToken.new(consumer, oauth_token, oauth_secret)
    # Make a request for JSON data
    names = csv(filepath)
    @profiles = []
    names.each do |aname|
      fname = aname[0]
      lname = aname.last
      query = ["first-name=#{fname}", "last-name=#{lname}"].join('&')
      fields = ['id','first-name', 'last-name', 'headline', 'location', 'relation-to-viewer', 'public-profile-url'].join(',') 
      json_txt = access_token.get("/v1/people-search:(people:(#{fields}))?#{query}", 'x-li-format' => 'json').body
      profile = JSON.parse(json_txt)
      parseddata = dataparse(profile)
      if parseddata != nil
        @profiles.push(parseddata)
      end
    end
    respond_to do |wants|
      # render in broswer
      wants.html
      wants.csv do
        # send it to the browser
        send_data gencsv(@profiles),
        :type => 'text/csv; charset=iso-8859-1; header=present',
        :disposition => "attachment; filename=users.csv"
      end
    end
  end

  def dataparse(data)
    puts "data"
    puts data.inspect
    if data["people"]["_total"] == 0
      return nil
    end
    dataprofiles = data["people"]["values"]
    @flatprofiles = []
    dataprofiles.each do |a|
      myprofile = {}
      myprofile["id"] = a["id"]
      myprofile["fname"] = a["firstName"]
      myprofile["lname"] = a["lastName"]
      myprofile["url"] = a["publicProfileUrl"]
      myprofile["desc"] = a["headline"]
      myprofile["location"] = a["location"]["name"]
      myprofile["conn"] = a["relationToViewer"]["distance"]
      @flatprofiles.push(myprofile)
    end
    @flatprofiles
  end

  def gencsv(data)
    csv_string = FasterCSV.generate do |csv|
      # header row
      csv << ["id", "first name", "last name", "description", "location", "connection", "url"]
      
      # data rows
      data.each do |a|
        a.each do |u|
          csv << [u["id"], u["fname"], u["lname"], u["desc"], u["location"], u["conn"].to_s, u["url"]]
        end
      end
    end
    csv_string
  end
end
